package org.jeecg.modules.demo.ddyht.controller;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.demo.ddyht.entity.DdygPayinfor;
import org.jeecg.modules.demo.ddyht.entity.DdygSale;
import org.jeecg.modules.demo.ddyht.entity.JxcHbzj;
import org.jeecg.modules.demo.ddyht.service.IDdygPayinforService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.demo.ddyht.service.IJxcHbzjService;
import org.jeecg.modules.demo.jxcx.Utils.R;
import org.jeecg.modules.demo.jxcx.Utils.RandomUtil;
import org.jeecg.modules.demo.jxcx.po.*;
import org.jeecg.modules.demo.jxcx.service.JxcCustomService;
import org.jeecg.modules.demo.jxcx.service.JxcCzrzService;
import org.jeecg.modules.demo.jxcx.service.JxcPayinforService;
import org.jeecg.modules.demo.jxcx.service.JxcSupplierService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;

 /**
 * @Description: 支付明细
 * @Author: jeecg-boot
 * @Date:   2025-03-15
 * @Version: V1.0
 */
@Api(tags="支付明细")
@RestController
@RequestMapping("/ddyht/jxcPayinfor")
@Slf4j
public class DdygPayinforController extends JeecgController<DdygPayinfor, IDdygPayinforService> {
	@Autowired
	private IDdygPayinforService ddygPayinforService;
	@Autowired
	private JxcPayinforService jxcPayinforService;
	@Autowired
	private JxcSupplierService jxcSupplierService;
	@Autowired
	private JxcCustomService jxcCustomService;
	@Autowired
	private JxcCzrzService jxcCzrzService;
	@Autowired
	private IJxcHbzjService jxcHbzjService;
     @Autowired
     private YueController yueController;

	/**
	 * 分页列表查询
	 *
	 * @param ddygPayinfor
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "支付明细-分页列表查询")
	@ApiOperation(value="支付明细-分页列表查询", notes="支付明细-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<DdygPayinfor>> queryPageList(DdygPayinfor ddygPayinfor,
													 @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
													 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
													 HttpServletRequest req) {
		QueryWrapper<DdygPayinfor> queryWrapper = QueryGenerator.initQueryWrapper(ddygPayinfor, req.getParameterMap());
		Page<DdygPayinfor> page = new Page<DdygPayinfor>(pageNo, pageSize);
		IPage<DdygPayinfor> pageList = ddygPayinforService.page(page, queryWrapper);
		List<DdygPayinfor> company = ddygPayinforService.getBycompany(ddygPayinfor.getUsername());
		int size = company.size();
		int page2 = (size + 9) / 10;
		pageList.setTotal(size);
		pageList.setPages(page2);
		pageList.setRecords(company);
		return Result.OK(pageList);
	}
	 @PostMapping(value = "/getBatchDetails")
	 public Result<List<JxcPayinfor>> getBatchDetails(@RequestBody JSONObject jsonObject) {
		 String companyId = jsonObject.getString("companyId");
		 String traner = jsonObject.getString("traner");
		 String orstate = jsonObject.getString("orstate");
		 List<JxcPayinfor> byall = jxcPayinforService.getByall(companyId, traner, orstate);
		 return Result.ok(byall);
	 }

	/**
	 *   添加
	 *
	 * @param jxcPayinfor
	 * @return
	 */
	@AutoLog(value = "支付明细-添加")
	@ApiOperation(value="支付明细-添加", notes="支付明细-添加")
//	@RequiresPermissions("ddyht:jxc_payinfor:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody DdygPayinfor jxcPayinfor) {
		LocalDateTime now = LocalDateTime.now();
		// 定义日期时间格式
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
		DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
		String formattedDateTime = now.format(formatter);
		String only1 = RandomUtil.generateRandomString();
		String id = now.format(formatter2) + only1;

		jxcPayinfor.setId(id);
		jxcPayinfor.setPaytime(formattedDateTime);

		String orstate = jxcPayinfor.getOrstate();
		String traner = jxcPayinfor.getOther().trim();
		String CompanyId = jxcPayinfor.getOtherid();
		String paymethod = jxcPayinfor.getPaymethod();
		String payamount1 = jxcPayinfor.getPayamount();
		BigDecimal payamount = new BigDecimal(jxcPayinfor.getPayamount());
		if (orstate.equals("1")){
			//供应商
			JxcSupplier jxcSupplier = jxcSupplierService.getBy(traner, CompanyId);
			if (jxcSupplier != null){
				BigDecimal oldSupplieramount = new BigDecimal(jxcSupplier.getAmount());
				jxcSupplier.setAmount(String.valueOf(oldSupplieramount.subtract(payamount)));
				jxcSupplier.setCreateTime(formattedDateTime);
				jxcSupplierService.updateById(jxcSupplier);

				JxcCzrz jxcCzrz1 = new JxcCzrz();
				jxcCzrz1.setId(DdygPiciController.setczrzid(id));
				jxcCzrz1.setCompanyId(CompanyId);
				jxcCzrz1.setInfor("交易方:"+traner+"金额-"+payamount);
				jxcCzrz1.setType("供应商修改");
				R add1 = jxcCzrzService.add(jxcCzrz1);


				if (jxcHbzjService.selectbyPaymentMethod(paymethod,CompanyId) != null){
					JxcHbzj jxcHbzj = jxcHbzjService.selectbyPaymentMethod(paymethod, CompanyId);
					jxcHbzj.setAmount(String.valueOf(new BigDecimal(jxcHbzj.getAmount()).subtract(payamount)));
					jxcHbzj.setCreateTime(formattedDateTime);
					jxcHbzjService.updateById(jxcHbzj);
				}else {
					JxcHbzj jxcHbzj2 = new JxcHbzj();
					jxcHbzj2.setAmount("-"+payamount);
					jxcHbzj2.setCompanyId(CompanyId);
					jxcHbzj2.setCreateTime(formattedDateTime);
					jxcHbzj2.setId(id);
					jxcHbzj2.setOther("应付明细支出");
					jxcHbzj2.setPaymethod(paymethod);
					jxcHbzjService.save(jxcHbzj2);

				}
				JxcCzrz jxcCzrz = new JxcCzrz();
				jxcCzrz.setId(DdygPiciController.setczrzid(id));
				jxcCzrz.setCompanyId(CompanyId);
				jxcCzrz.setOtherid("货币资金");
				jxcCzrz.setOrstate("应付明细支出-"+traner);
				jxcCzrz.setType(paymethod);
				jxcCzrz.setInfor("-" + payamount1);
				jxcCzrz.setCreatTime(formattedDateTime);
                yueController.setHbzj(jxcCzrz,paymethod,payamount1,"-");
				jxcCzrzService.add(jxcCzrz);
			}
		}else {
			JxcCustom jxcCustom = jxcCustomService.getBy(traner, CompanyId);
			if (jxcCustom != null){
				BigDecimal oldCustomamount = new BigDecimal(jxcCustom.getAmount());
				jxcCustom.setAmount(String.valueOf(oldCustomamount.subtract(payamount)));
				jxcCustom.setCreateTime(formattedDateTime);
				jxcCustomService.updateById(jxcCustom);

				JxcCzrz jxcCzrz1 = new JxcCzrz();
				jxcCzrz1.setId(DdygPiciController.setczrzid(id));
				jxcCzrz1.setCompanyId(CompanyId);
				jxcCzrz1.setInfor("交易方:"+traner+"金额-"+payamount);
				jxcCzrz1.setType("客户修改");
				R add1 = jxcCzrzService.add(jxcCzrz1);

				if (jxcHbzjService.selectbyPaymentMethod(paymethod,CompanyId) != null){
					JxcHbzj jxcHbzj = jxcHbzjService.selectbyPaymentMethod(paymethod, CompanyId);
					jxcHbzj.setAmount(String.valueOf(new BigDecimal(jxcHbzj.getAmount()).add(payamount)));
					jxcHbzj.setCreateTime(formattedDateTime);
					jxcHbzjService.updateById(jxcHbzj);
				}else {
					JxcHbzj jxcHbzj2 = new JxcHbzj();
					jxcHbzj2.setAmount(""+payamount);
					jxcHbzj2.setCompanyId(CompanyId);
					jxcHbzj2.setCreateTime(formattedDateTime);
					jxcHbzj2.setId(id);
					jxcHbzj2.setOther("应收明细收入");
					jxcHbzj2.setPaymethod(paymethod);
					jxcHbzjService.save(jxcHbzj2);

				}
				JxcCzrz jxcCzrz = new JxcCzrz();
				jxcCzrz.setId(DdygPiciController.setczrzid(id));
				jxcCzrz.setCompanyId(CompanyId);
				jxcCzrz.setOtherid("货币资金");
				jxcCzrz.setOrstate("应收明细收入-"+traner);
				jxcCzrz.setType(paymethod);
				jxcCzrz.setInfor("+" + payamount1);
				jxcCzrz.setCreatTime(formattedDateTime);
                yueController.setHbzj(jxcCzrz,paymethod,payamount1,"+");
				jxcCzrzService.add(jxcCzrz);
			}

		}
		JxcCzrz jxcCzrz = new JxcCzrz();
		jxcCzrz.setId(DdygPiciController.setczrzid(id));
		jxcCzrz.setCompanyId(CompanyId);
		jxcCzrz.setInfor("交易方:"+traner+"金额:"+payamount);
		jxcCzrz.setType("付款明细新增");
		R add = jxcCzrzService.add(jxcCzrz);
//		jxcPayinforService.save(jxcPayinfor);
		ddygPayinforService.save(jxcPayinfor);
		return Result.OK(id);
	}

	/**
	 *  编辑
	 *
	 * @param jxcPayinfor
	 * @return
	 */
	@AutoLog(value = "支付明细-编辑")
	@ApiOperation(value="支付明细-编辑", notes="支付明细-编辑")
//	@RequiresPermissions("ddyht:jxc_payinfor:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody DdygPayinfor jxcPayinfor) {
		String orstate = jxcPayinfor.getOrstate();
		String companyId = jxcPayinfor.getOtherid();
		BigDecimal payamount = new BigDecimal(jxcPayinfor.getPayamount());
		String traner = jxcPayinfor.getOther().trim();
		String id = jxcPayinfor.getId();

		//旧数据
		JxcPayinfor oldJxcPayinfor = jxcPayinforService.getById(jxcPayinfor.getId());
		BigDecimal oldpayamount = new BigDecimal(oldJxcPayinfor.getPayamount());

		JxcCzrz jxcCzrz = new JxcCzrz();
		jxcCzrz.setId(DdygPiciController.setczrzid(id));
		jxcCzrz.setCompanyId(companyId);
		jxcCzrz.setInfor("交易方:"+traner+"金额:"+oldpayamount + "->"+payamount);
		jxcCzrz.setType("付款明细修改");
		R add = jxcCzrzService.add(jxcCzrz);
		//如果比原来多
		if (payamount.compareTo(oldpayamount) > 0){
			//差值
			BigDecimal diff = payamount.subtract(oldpayamount);
			if (orstate.equals("1")){
				//供应商
				JxcSupplier jxcSupplier = jxcSupplierService.getBy(traner, companyId);
				if (jxcSupplier != null){
					BigDecimal oldSupplieramount = new BigDecimal(jxcSupplier.getAmount());
					jxcSupplier.setAmount(String.valueOf(oldSupplieramount.subtract(diff)));
					jxcSupplierService.updateById(jxcSupplier);

					JxcCzrz jxcCzrz1 = new JxcCzrz();
					jxcCzrz1.setId(DdygPiciController.setczrzid(id));
					jxcCzrz1.setCompanyId(companyId);
					jxcCzrz1.setInfor("交易方:"+traner+"金额+"+String.valueOf(diff));
					jxcCzrz1.setType("供应商修改");
					R add1 = jxcCzrzService.add(jxcCzrz1);
				}
				JxcCzrz czrz = jxcCzrzService.getByIdAndOther(id, "货币资金", companyId);
				if (czrz != null){
					czrz.setInfor(String.valueOf(new BigDecimal(czrz.getInfor()).subtract(diff)));
				}
				jxcCzrzService.updateById(czrz);
				JxcHbzj jxcHbzj = jxcHbzjService.selectbyPaymentMethod(jxcPayinfor.getPaymethod(), companyId);
				if (jxcHbzj != null){
					jxcHbzj.setAmount(String.valueOf(new BigDecimal(jxcHbzj.getAmount()).subtract(diff)));
				}
				jxcHbzjService.updateById(jxcHbzj);


			}else {
				JxcCustom jxcCustom = jxcCustomService.getBy(traner, companyId);
				if (jxcCustom != null){
					BigDecimal oldCustomamount = new BigDecimal(jxcCustom.getAmount());
					jxcCustom.setAmount(String.valueOf(oldCustomamount.subtract(diff)));
					jxcCustomService.updateById(jxcCustom);

					JxcCzrz jxcCzrz1 = new JxcCzrz();
					jxcCzrz1.setId(DdygPiciController.setczrzid(id));
					jxcCzrz1.setCompanyId(companyId);
					jxcCzrz1.setInfor("交易方:"+traner+"金额+"+String.valueOf(diff));
					jxcCzrz1.setType("客户修改");
					R add1 = jxcCzrzService.add(jxcCzrz1);
				}

				JxcCzrz czrz = jxcCzrzService.getByIdAndOther(id, "货币资金", companyId);
				if (czrz != null){
					czrz.setInfor(String.valueOf(new BigDecimal(czrz.getInfor()).add(diff)));
				}
				jxcCzrzService.updateById(czrz);
				JxcHbzj jxcHbzj = jxcHbzjService.selectbyPaymentMethod(jxcPayinfor.getPaymethod(), companyId);
				if (jxcHbzj != null){
					jxcHbzj.setAmount(String.valueOf(new BigDecimal(jxcHbzj.getAmount()).add(diff)));
				}
				jxcHbzjService.updateById(jxcHbzj);
			}
		}else if (payamount.compareTo(oldpayamount) < 0){
			//差值
			BigDecimal diff = oldpayamount.subtract(payamount);
			if (orstate.equals("1")){
				JxcSupplier jxcSupplier = jxcSupplierService.getBy(traner, companyId);
				if (jxcSupplier != null){
					BigDecimal oldSupplieramount = new BigDecimal(jxcSupplier.getAmount());
					jxcSupplier.setAmount(String.valueOf(oldSupplieramount.add(diff)));
					jxcSupplierService.updateById(jxcSupplier);

					JxcCzrz jxcCzrz1 = new JxcCzrz();
					jxcCzrz1.setId(DdygPiciController.setczrzid(id));
					jxcCzrz1.setCompanyId(companyId);
					jxcCzrz1.setInfor("交易方:"+traner+"金额-"+String.valueOf(diff));
					jxcCzrz1.setType("供应商修改");
					R add1 = jxcCzrzService.add(jxcCzrz1);
				}

				JxcCzrz czrz = jxcCzrzService.getByIdAndOther(id, "货币资金", companyId);
				if (czrz != null){
					czrz.setInfor(String.valueOf(new BigDecimal(czrz.getInfor()).add(diff)));
				}
				jxcCzrzService.updateById(czrz);
				JxcHbzj jxcHbzj = jxcHbzjService.selectbyPaymentMethod(jxcPayinfor.getPaymethod(), companyId);
				if (jxcHbzj != null){
					jxcHbzj.setAmount(String.valueOf(new BigDecimal(jxcHbzj.getAmount()).add(diff)));
				}
				jxcHbzjService.updateById(jxcHbzj);
			}else {
				JxcCustom jxcCustom = jxcCustomService.getBy(traner, companyId);
				if (jxcCustom != null){
					BigDecimal oldCustomamount = new BigDecimal(jxcCustom.getAmount());
					jxcCustom.setAmount(String.valueOf(oldCustomamount.add(diff)));
					jxcCustomService.updateById(jxcCustom);

					JxcCzrz jxcCzrz1 = new JxcCzrz();
					jxcCzrz1.setId(DdygPiciController.setczrzid(id));
					jxcCzrz1.setCompanyId(companyId);
					jxcCzrz1.setInfor("交易方:"+traner+"金额-"+String.valueOf(diff));
					jxcCzrz1.setType("客户修改");
					R add1 = jxcCzrzService.add(jxcCzrz1);
				}

				JxcCzrz czrz = jxcCzrzService.getByIdAndOther(id, "货币资金", companyId);
				if (czrz != null){
					czrz.setInfor(String.valueOf(new BigDecimal(czrz.getInfor()).subtract(diff)));
				}
				jxcCzrzService.updateById(czrz);
				JxcHbzj jxcHbzj = jxcHbzjService.selectbyPaymentMethod(jxcPayinfor.getPaymethod(), companyId);
				if (jxcHbzj != null){
					jxcHbzj.setAmount(String.valueOf(new BigDecimal(jxcHbzj.getAmount()).subtract(diff)));
				}
				jxcHbzjService.updateById(jxcHbzj);
			}
		}

		ddygPayinforService.updateById(jxcPayinfor);
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "支付明细-通过id删除")
	@ApiOperation(value="支付明细-通过id删除", notes="支付明细-通过id删除")
//	@RequiresPermissions("ddyht:jxc_payinfor:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
//		JSONArray idList = params.getJSONArray("idList");

		//去除空格

		log.info("付款详情删除数据"+id.toString());
//		String id = idList.get(0).toString();
		JxcPayinfor jxcPayinfor = jxcPayinforService.getById(id);
		String orstate = jxcPayinfor.getOrstate();
		String companyId = jxcPayinfor.getOtherid();
		BigDecimal payamount = new BigDecimal(jxcPayinfor.getPayamount());
		String traner = jxcPayinfor.getOther().trim();

		JxcCzrz jxcCzrz = new JxcCzrz();
		jxcCzrz.setId(DdygPiciController.setczrzid(id));
		jxcCzrz.setCompanyId(companyId);
		jxcCzrz.setInfor("交易方:"+traner+"金额:"+payamount);

		if (orstate.equals("1")){
			jxcCzrz.setType("供应商付款明细删除");
			R add = jxcCzrzService.add(jxcCzrz);
			//供应商
			JxcSupplier jxcSupplier = jxcSupplierService.getBy(traner, companyId);
			if (jxcSupplier != null){
				BigDecimal oldSupplieramount = new BigDecimal(jxcSupplier.getAmount());
				jxcSupplier.setAmount(String.valueOf(oldSupplieramount.add(payamount)));
				jxcSupplierService.updateById(jxcSupplier);

				JxcCzrz jxcCzrz1 = new JxcCzrz();
				jxcCzrz1.setId(DdygPiciController.setczrzid(id));
				jxcCzrz1.setCompanyId(companyId);
				jxcCzrz1.setInfor("交易方:"+traner+"金额:+"+jxcPayinfor.getPayamount());
				jxcCzrz1.setType("供应商修改");
				R add1 = jxcCzrzService.add(jxcCzrz1);
			}
		}else {
			jxcCzrz.setType("客户付款明细删除");
			R add = jxcCzrzService.add(jxcCzrz);
			JxcCustom jxcCustom = jxcCustomService.getBy(traner, companyId);
			if (jxcCustom != null){
				BigDecimal oldCustomamount = new BigDecimal(jxcCustom.getAmount());
				jxcCustom.setAmount(String.valueOf(oldCustomamount.add(payamount)));
				jxcCustomService.updateById(jxcCustom);

				JxcCzrz jxcCzrz1 = new JxcCzrz();
				jxcCzrz1.setId(DdygPiciController.setczrzid(id));
				jxcCzrz1.setCompanyId(companyId);
				jxcCzrz1.setInfor("交易方:"+traner+"金额:+"+jxcPayinfor.getPayamount());
				jxcCzrz1.setType("客户修改");
				R add1 = jxcCzrzService.add(jxcCzrz1);
			}
		}
		ddygPayinforService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "支付明细-批量删除")
	@ApiOperation(value="支付明细-批量删除", notes="支付明细-批量删除")
	@RequiresPermissions("ddyht:jxc_payinfor:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.ddygPayinforService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "支付明细-通过id查询")
	@ApiOperation(value="支付明细-通过id查询", notes="支付明细-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<DdygPayinfor> queryById(@RequestParam(name="id",required=true) String id) {
		DdygPayinfor ddygPayinfor = ddygPayinforService.getById(id);
		if(ddygPayinfor ==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(ddygPayinfor);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param ddygPayinfor
    */
    @RequiresPermissions("ddyht:jxc_payinfor:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, DdygPayinfor ddygPayinfor) {
        return super.exportXls(request, ddygPayinfor, DdygPayinfor.class, "支付明细");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequiresPermissions("ddyht:jxc_payinfor:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, DdygPayinfor.class);
    }

}
